/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.presenter;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.HttpSession;
import org.zhiqim.httpd.HttpSessionManager;
import org.zhiqim.httpd.HttpSessionUser;
import org.zhiqim.httpd.context.ZmlContexts;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.extend.HashMapSO;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.ZmrConstants;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dao.ZmrOperatorDao;
import org.zhiqim.manager.dbo.ZmrOperator;
import org.zhiqim.manager.dbo.ZmrOperatorLog;
import org.zhiqim.manager.dbo.ZmrParamOperator;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 操作员控制器，四个方法：
 * 1、验证密码
 * 2、查询操作日志
 * 3、踢除用户下线
 * 比ZhiqimAdmin多一个方法
 * 4、更新操作员参数
 *
 * @version v1.0.0 @author zouzhigang 2017-6-6 新建与整理
 */
@AnAlias("ZmrOperatorPresenter")
@AnIntercept("chkZmrLogin")
public class ZmrOperatorPresenter implements ZmrConstants
{
    /**
     * 验证操作员密码
     * 
     * @param request       请求
     * @param operatorPass  密码
     */
    public static void doValidatePassword(HttpRequest request, String operatorPass)
    {
        if (Validates.isEmptyBlank(operatorPass))
        {
            request.setResponseError("密码不允许为空白");
            return;
        }
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        if (!ZmrOperatorDao.validatePassword(request, sessionUser.getOperator(), operatorPass))
        {
            request.setResponseError("密码不正确");
        }
    }
    
    /**
     * 查询操作日志
     * 
     * @param request       请求对象
     * @throws Exception    异常
     */
    public static String doQueryOperateLog(HttpRequest request) throws Exception
    {
        int page = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt(ZMR_PAGE_SIZE, 20);
        String beginTime = request.getParameter("beginTime", DateTimes.getPreviousDateTimeString());
        String endTime = request.getParameter("endTime", DateTimes.getDateTimeString());
        String operateFeature = request.getParameter("operateFeature");
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        
        Selector selector = new Selector();
        selector.addMaybeThenGE("operateTime", Sqls.toTimestamp(beginTime));
        selector.addMaybeThenLE("operateTime", Sqls.toTimestamp(endTime));
        if (!sessionUser.isAdmin())
        {//操作员只能查看自己的
            selector.addMust("operatorCode", sessionUser.getOperatorCode());
        }
        else
        {//查操作员
            selector.addMaybe("operatorCode", request.getParameter("operatorCode"));
        }
        selector.addMaybeLike("operateFeature", operateFeature);
        selector.addOrderbyDesc("operateTime");
        
        PageResult<ZmrOperatorLog> result = ORM.table().page(ZmrOperatorLog.class, page, pageSize, selector);
        result.addConditionMap(request.getParameterMap());
        
        return ZmlContexts.parseZmlPath(request, "/zview/zhiqim_manager/presenter/operateLogInfo.zml", "result", result);
    }
    
    /**
     * 剔除在线用户
     * 
     * @param request       请求对象
     * @param sessionId     用户会话编号
     * @throws Exception    异常
     */
    public static void doRemoveOnlineOperator(HttpRequest request, String sessionId) throws Exception
    {
        HttpSessionManager manager = request.getContext().getSessionManager();
        HttpSession session = manager.getSession(sessionId);
        if (session == null)
            return;
        
        HttpSessionUser sessionUser = session.getSessionUser();
        String json = sessionUser == null?Jsons.toString("sessionId", sessionId):Jsons.toString("operatorCode", sessionUser.getSessionName(), "sessionId", sessionId);
        
        request.getContext().getSessionManager().invalidateSession(sessionId);
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "踢操作员下线", json);
    }
    
    /********************************************************************************************/
    //相对（Zhiqim Admin）多一个更新操作员参数功能
    /********************************************************************************************/

    /**
     * 更新操作员参数
     * 
     * @param request       请求对象
     * @throws Exception    异常
     */
    public static void doUpdateOperatorParam(HttpRequest request) throws Exception
    {
        String paramKey = request.getParameter("paramKey");
        String paramValue = request.getParameter("paramValue");
        
        if(ORM.table().count(ZmrParamOperator.class, paramKey) <= 0)
        {
            request.setResponseError("该操作员参数键未定义，请重新输入");
            return;
        }
        
        String operatorCode = request.getParameter("operatorCode");
        if (ORM.table().count(ZmrOperator.class, operatorCode) <= 0)
        {
            request.setResponseError("请选择一个有效的操作员");
            return;
        }
        
        ZmrOperatorDao.addOrUpdateOperatorParam(request, operatorCode, paramKey, paramValue);
        
        //增加操作日志
        MapSO map = new HashMapSO(3);
        map.put("operatorCode", operatorCode);
        map.put("paramKey", paramKey);
        map.put("paramValue", paramValue);
        
        ZmrOperatorDao.addOperateLog(request, "修改操作员参数", Jsons.toString(map));
    }
}
